<?php

namespace plugin\ycMassage\app\shop\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageMch;
use plugin\ycMassage\app\model\MassageMchBill;
use plugin\ycMassage\app\model\MassageShop;
use plugin\ycMassage\app\model\MassageShopBill;
use plugin\ycMassage\app\model\MassageShopStatistics;
use plugin\ycMassage\app\model\MassageUserTechnician;
use plugin\ycMassage\app\model\MassageUserTechnicianBill;
use plugin\ycMassage\app\model\MassageUserTechnicianStatistics;
use plugin\ycMassage\app\model\MassageUserWallet;
use plugin\ycMassage\utils\enum\MoneyAction;
use support\Request;
use think\facade\Db;

class UserWalletController extends BaseController
{
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addColumn('uid', 'UID', [
            'width' => 90
        ])
            ->addColumn('mobile', '手机号', [
                'width' => 120
            ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120
            ])
            ->addColumn('money', '变动金额', [
                'width' => 120
            ])
            ->addColumn('old_money', '变动前', [
                'width' => 120
            ])
            ->addColumn('new_money', '变动后', [
                'width' => 120
            ])
            ->addColumnEle('action', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => MoneyAction::dictOptions(),
                    'style' => MoneyAction::dictOptions('style'),
                ],
            ])
            ->addColumn('remarks', '备注')
            ->addColumn('create_time', '时间', [
                'width' => 160
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['log.saas_appid', '=', $request->saas_appid]
        ];
        $where[] = ['log.uid', '=', $request->uid];
        if ($request->use_mch_id) {
            $model = MassageMchBill::class;
        } else {
            $model = MassageShopBill::class;
        }
        $data = $model::where($where)
            ->alias('log')
            ->join('massage_user u', 'log.uid=u.id', 'LEFT')
            ->order('log.id desc')
            ->field('log.*,u.mobile,u.nickname,u.headimg')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                $item->nickname = base64_decode($item->nickname);
                if (strpos($item->headimg, 'http') !== 0) {
                    $item->headimg = UploadService::url($item->headimg);
                }
            });
        return $this->successRes($data);
    }
    public function technician(Request $request)
    {
        $uid = $request->get('id');
        $where = [
            ['t.uid', '=', $uid],
            ['t.saas_appid', '=', $request->saas_appid],
            ['t.work_mch_id', '=', $request->use_mch_id]
        ];
        $MassageUserTechnician = MassageUserTechnician::where($where)
            ->alias('t')
            ->join('massage_user u', 'u.id = t.uid')
            ->field('t.*,u.headimg,u.nickname')
            ->find();
        if (!$MassageUserTechnician) {
            return $this->fail('技师不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            Db::startTrans();
            try {
                $commission = abs((float)$D['money']);
                $MassageMch = MassageMch::where(['id' => $request->use_mch_id])->find();
                if (!$MassageMch) {
                    throw new \Exception('商户不存在');
                }
                MassageMchBill::decrease("商户分账给技师：{$MassageUserTechnician['name']}", $MassageMch->uid, $commission);
                MassageUserTechnicianBill::increase("来自商户：{$MassageMch->title}的分账", $MassageUserTechnician->uid, $commission, $MassageMch->uid);
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
            return $this->success('保存成功');
        }
        if ($MassageUserTechnician->nickname) {
            $MassageUserTechnician->nickname = base64_decode($MassageUserTechnician->nickname);
        }
        if (strpos($MassageUserTechnician->headimg, 'http') !== 0) {
            $MassageUserTechnician->headimg = UploadService::url($MassageUserTechnician->headimg);
        }
        $MassageUserTechnicianStatistics = MassageUserTechnicianStatistics::where(['uid' => $MassageUserTechnician->uid])->whereMonth('create_time')->select();
        $MassageUserTechnician->month_order_num = 0;
        $MassageUserTechnician->month_order_price = 0;
        $MassageUserTechnician->month_duration = 0;
        foreach ($MassageUserTechnicianStatistics as $key => $value) {
            $MassageUserTechnician->month_order_num += $value->order_num;
            $MassageUserTechnician->month_order_price += $value->order_price;
            $MassageUserTechnician->month_duration += $value->duration;
        }
        $MassageUserTechnicianStatistics = MassageUserTechnicianStatistics::where(['uid' => $MassageUserTechnician->uid])->whereMonth('create_time', 'last month')->select();
        $MassageUserTechnician->last_month_order_num = 0;
        $MassageUserTechnician->last_month_order_price = 0;
        $MassageUserTechnician->last_month_duration = 0;
        foreach ($MassageUserTechnicianStatistics as $key => $value) {
            $MassageUserTechnician->last_month_order_num += $value->order_num;
            $MassageUserTechnician->last_month_order_price += $value->order_price;
            $MassageUserTechnician->last_month_duration += $value->duration;
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('headimg', 'el-avatar', '头像', '', [
            'col'           => 6,
            'props'         => [
                'src'       => $MassageUserTechnician->headimg,
                'width'     => 100,
                'height'    => 100
            ]
        ]);
        $builder->addComponent('nickname', 'info', '昵称', '', [
            'col'           => 8,
        ]);
        $builder->addComponent('name', 'info', '姓名', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('uid', 'info', 'UID', '', [
            'col'           => 4,
        ]);
        $builder->addDivider('本月业绩');
        $builder->addComponent('month_order_num', 'info', '订单数', '', [
            'col'           => 8,
        ]);
        $builder->addComponent('month_order_price', 'info', '订单额', '', [
            'col'           => 8,
        ]);
        $builder->addComponent('month_duration', 'info', '服务时长', '', [
            'col'           => 8,
        ]);
        $builder->addDivider('上月业绩');
        $builder->addComponent('last_month_order_num', 'info', '订单数', '', [
            'col'           => 8,
        ]);
        $builder->addComponent('last_month_order_price', 'info', '订单额', '', [
            'col'           => 8,
        ]);
        $builder->addComponent('last_month_duration', 'info', '服务时长', '', [
            'col'           => 8,
        ]);
        $builder->addDivider('分账');
        $builder->addRow('money', 'number', '金额', '', [
            'col' => 12,
            'props' => [
                'controls' => false,
                'min' => 0,
                'step' => 0.01,
                'precision' => 2
            ]
        ]);
        $data = $builder->setData($MassageUserTechnician)->create();
        return $this->successRes($data);
    }
    public function shop(Request $request)
    {
        $id = $request->get('id');
        $where = [
            ['s.id', '=', $id],
            ['s.saas_appid', '=', $request->saas_appid],
            ['s.mch_id', '=', $request->use_mch_id]
        ];
        $MassageShop = MassageShop::where($where)
            ->alias('s')
            ->join('massage_user u', 'u.id = s.uid')
            ->field('s.*,u.headimg,u.nickname')
            ->find();
        if (!$MassageShop) {
            return $this->fail('门店不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            Db::startTrans();
            try {
                $commission = abs((float)$D['money']);
                $MassageMch = MassageMch::where(['id' => $request->use_mch_id])->find();
                if (!$MassageMch) {
                    throw new \Exception('商户不存在');
                }
                MassageMchBill::decrease("{$MassageMch->title}商户分账给门店：{$MassageShop['title']}", $MassageMch->uid, $commission);
                MassageShopBill::increase("来自商户：{$MassageMch->title}的分账，{$MassageShop->title}门店", $MassageShop->uid, $commission, $MassageMch->uid);
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
            return $this->success('保存成功');
        }
        if ($MassageShop->nickname) {
            $MassageShop->nickname = base64_decode($MassageShop->nickname);
        }
        if (strpos($MassageShop->headimg, 'http') !== 0) {
            $MassageShop->headimg = UploadService::url($MassageShop->headimg);
        }
        if (strpos($MassageShop->logo, 'http') !== 0) {
            $MassageShop->logo = UploadService::url($MassageShop->logo);
        }
        $MassageShopStatistics = MassageShopStatistics::where(['shop_id' => $MassageShop->id])->whereMonth('create_time')->select();
        $MassageShop->month_person_time = 0;
        $MassageShop->month_order_num = 0;
        $MassageShop->month_order_price = 0;
        $MassageShop->month_duration = 0;
        foreach ($MassageShopStatistics as $key => $value) {
            $MassageShop->month_person_time += $value->person_time;
            $MassageShop->month_order_num += $value->orders_num;
            $MassageShop->month_order_price += $value->orders_price;
            $MassageShop->month_duration += $value->duration;
        }
        $MassageShopStatistics = MassageShopStatistics::where(['shop_id' => $MassageShop->id])->whereMonth('create_time', 'last month')->select();
        $MassageShop->last_month_person_time = 0;
        $MassageShop->last_month_order_num = 0;
        $MassageShop->last_month_order_price = 0;
        $MassageShop->last_month_duration = 0;
        foreach ($MassageShopStatistics as $key => $value) {
            $MassageShop->last_month_person_time += $value->person_time;
            $MassageShop->last_month_order_num += $value->orders_num;
            $MassageShop->last_month_order_price += $value->orders_price;
            $MassageShop->last_month_duration += $value->duration;
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('headimg', 'el-avatar', '头像', '', [
            'col'           => 6,
            'props'         => [
                'src'       => $MassageShop->headimg,
                'width'     => 100,
                'height'    => 100
            ]
        ]);
        $builder->addComponent('nickname', 'info', '店长', '', [
            'col'           => 8,
        ]);
        $builder->addComponent('uid', 'info', 'UID', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('logo', 'el-avatar', 'LOGO', '', [
            'col'           => 6,
            'props'         => [
                'src'       => $MassageShop->logo,
                'width'     => 100,
                'height'    => 100
            ]
        ]);
        $builder->addComponent('title', 'info', '门店', '', [
            'col'           => 8,
        ]);
        $builder->addComponent('id', 'info', '门店ID', '', [
            'col'           => 6,
        ]);
        $builder->addDivider('本月业绩');
        $builder->addComponent('month_person_time', 'info', '人次', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('month_order_num', 'info', '订单数', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('month_order_price', 'info', '订单额', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('month_duration', 'info', '服务时长', '', [
            'col'           => 6,
        ]);
        $builder->addDivider('上月业绩');
        $builder->addComponent('last_month_person_time', 'info', '人次', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('last_month_order_num', 'info', '订单数', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('last_month_order_price', 'info', '订单额', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('last_month_duration', 'info', '服务时长', '', [
            'col'           => 6,
        ]);
        $builder->addDivider('分账');
        $builder->addRow('money', 'number', '金额', '', [
            'col' => 12,
            'props' => [
                'controls' => false,
                'min' => 0,
                'step' => 0.01,
                'precision' => 2
            ]
        ]);
        $data = $builder->setData($MassageShop)->create();
        return $this->successRes($data);
    }
}
